<?php
/*	Created by Alexander Alexandrov aka SS
			hazg@mail.ru				*/
			
	class Folder 
	{
		private $scanned = false;
		private $path = '';
		
		protected $files = array();
		protected $folders = array();
		private $parent = null;
		const RECURSE_NONE = 0;
		const RECURSE_LIST = 1;

		
		static function Create($path)
		{
		    $folder = explode( "/" , $path );
            $mkfolder = '';
            for(  $i=0 ; isset( $folder[$i] ) ; $i++ )
            {
                $mkfolder .= $folder[$i] . '/';
                if( !is_dir( $mkfolder ) )
                    mkdir( "$mkfolder" ,  0777);
            }
		}
		
		
		function __toString(){return $this->path;}
		 
		function Folder($path, $type = Folder::RECURSE_NONE, $parent = null) 
		{
			$this->parent = $parent;
			$pi = pathinfo($path);

			$this->path = $pi['dirname'].'/'.$pi['basename'];

			if(!is_dir($this->path)) new Err(__T('wrong path'));
			
			
			switch($type)
			{
				case Folder::RECURSE_LIST:
					{
						$folders = $this->Folders(Folder::RECURSE_LIST, $this);
						foreach($folders as $folder)
						{
							$this->folders = array_merge($this->Folders(), $folder->Folders());
							$this->files = array_merge($this->Files(), $folder->Files());
						}
						if($this->parent !== null)
						{
							unset($this->files);
							unset($this->folders);
						}
						break;
					}
				case Folder::RECURSE_NONE:
					{
						break;
					}
				default: new Err(__T('wrong datatype'));
			}
		}
		function Files()
		{
			if(!$this->scanned){$this->scan();}
			return $this->files;
		}
		function Folders()
		{
			if(!$this->scanned){$this->scan();}
			return $this->folders;
		}
		//TODO: Кросплатформенный путь "/" "\"
		private function scan()
		{
			if ($d = opendir($this->path)) 
		    {
		        while (($f = readdir($d)) !== false)
		        {
		        	
		        	if(is_dir($this->path.'/'.$f)){if($f !== '..' && $f !== '.')$this->folders[] = new Folder($this->path.'/'.$f);}
		        	else $this->files[] = $this->path.'/'.$f;
		        }
		        closedir($d);
		    }
		    $this->scanned = true;
		}
	}
?>